package com.googlecode.yonggemovie.widgets.player;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.WindowConstants;

public class PlayerPanel extends javax.swing.JPanel {
	private VideoPanel videoPanel;
	private JButton fileBtn;
	private JPanel progressPanel;
	private JProgressBar progressBar;
	private JPanel btnPanel;
	private JButton stopBtn;
	private JButton playBtn;
	private JPanel controlPanel;


	private String[] cmd;
	private Process proc;
	private Thread t1;
	private Thread t2;

	private static final String MPLAYER_PATH = "mplayer/mplayer.exe";//mplayer程序路径
	private String mediaPath = "";//播放文件路径
	private int length = 0;//视频长度，单位秒
	private int videoWidth;//视频宽
	private int videoHeight;//视频高
	private float rate = 1.2f;//宽高比
	private int playOffset = 0;//当前播放时间，这个值是不断变化的
	private int volume = 100;//音量

	//播放器状态
	private boolean isPlay = false;
	private boolean isPause = false;
	
	
	
	public static void main(String[] args) {
		JFrame frame = new JFrame();
		final PlayerPanel player = new PlayerPanel();
		frame.getContentPane().add(player);
		frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
		frame.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				player.exit();
			}	
		});
		
		frame.pack();
		frame.setVisible(true);
	}
	
	public PlayerPanel() {
		super();
		initGUI();
	}
	
	private void initGUI() {
		try {
			BorderLayout thisLayout = new BorderLayout();
			this.setLayout(thisLayout);
			setPreferredSize(new Dimension(400, 300));
			{
				videoPanel = new VideoPanel(this);
				this.add(videoPanel, BorderLayout.CENTER);
				videoPanel.setPreferredSize(new java.awt.Dimension(400, 235));
			}
			{
				controlPanel = new JPanel();
				BorderLayout controlPanelLayout = new BorderLayout();
				controlPanel.setLayout(controlPanelLayout);
				this.add(controlPanel, BorderLayout.SOUTH);
				{
					progressPanel = new JPanel();
					controlPanel.add(progressPanel, BorderLayout.NORTH);
					{
						progressBar = new JProgressBar();
						progressPanel.add(progressBar);
						progressBar.setPreferredSize(new java.awt.Dimension(358, 14));
					}
				}
				{
					btnPanel = new JPanel();
					FlowLayout btnPanelLayout = new FlowLayout();
					btnPanel.setLayout(btnPanelLayout);
					controlPanel.add(btnPanel, BorderLayout.CENTER);
					{
						fileBtn = new JButton();
						btnPanel.add(fileBtn);
						fileBtn.setText("Open");
						fileBtn.addActionListener(new ActionListener() {
							public void actionPerformed(ActionEvent evt) {
								fileBtnActionPerformed(evt);
							}
						});
					}
					{
						playBtn = new JButton();
						btnPanel.add(playBtn);
						playBtn.setText("Play");
					}
					{
						stopBtn = new JButton();
						btnPanel.add(stopBtn);
						stopBtn.setText("Stop");
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void fileBtnActionPerformed(ActionEvent evt) {
		JFileChooser fc = new JFileChooser();
		int state = fc.showOpenDialog(fileBtn);
		if(state == JFileChooser.APPROVE_OPTION) {
			File file = fc.getSelectedFile();
			this.play(file.getAbsolutePath());
			
		}else {
			return;
		}
		
	}
	
	//播放文件
	public void play(String path){
		//stop();
		//mediaPath=path;
		//isPlay=true;
		//button_Play.setText("Pause");
		//调用命令行,更多选项可参考mplayer文档
		cmd = new String[] {
				MPLAYER_PATH,//mplayer路径
				"-vo","directx",//视频驱动
				"-identify", //输出详情
				"-slave", //slave模式播放
				"-wid",String.valueOf(videoPanel.getWid()),//视频窗口的window handle，这个是关键点，即指定播放器的视频内容在哪里显示，如果不指定，windows下会自动弹出一个默认的windows窗口。
				"-colorkey", "0x030303",//视频窗口的背景色
				"-osdlevel", String.valueOf(1),//osd样式
				path //播放文件路径
		};
		try {
			proc = Runtime.getRuntime().exec(cmd);
		} catch (IOException e1) {
			e1.printStackTrace();
			return;
		}

		//读取并解析mplayer的输出信息
		final InputStream is1 = proc.getErrorStream();
		final InputStream is2 = proc.getInputStream();
		final Runnable errorReader = new Runnable() {
			public void run() {
				try {
					final BufferedReader lReader = new BufferedReader(new InputStreamReader(is1));
					for (String l = lReader.readLine(); l != null ; l = lReader.readLine()) {
						// System.out.println("ERROR "+l);
					}
				} catch (Throwable t) {
					t.printStackTrace();
				}
			}
		};


		final Runnable standReader = new Runnable() {
			public void run() {
				try {
					final BufferedReader lReader = new BufferedReader(new InputStreamReader(is2));
					String l="";
					while ((l=lReader.readLine())!=null) {
						//System.out.println(l);
						
						//解析总的播放时间（单位秒）
						if (l.length() >= 10) {
							String s2 = l.substring(0, 9);
							if (s2.equals("ID_LENGTH")) {
								int index = l.indexOf(".");
								String s1 = l.substring(10,index);
								length = Integer.valueOf(s1);
							}
						}
						//解析当前播放时间（单位秒）
						if(l.length()>70&&l.startsWith("A:")){
							int index = l.indexOf(".");
							String s3 = l.substring(2, index);
							int index2 = 0;
							while (true) {
								int index3 = s3.indexOf(" ", index2);
								if (index3 != -1) {
									index2 = index3 + 1;
								} else {
									break;
								}
							}
							String s4 = s3.substring(index2);
							playOffset = Integer.valueOf(s4);//这个值是不断变化的
						}
						//解析视频宽度						
						if (l.length() >= 14) {
							String s3 = l.substring(0, 14);
							if (s3.equals("ID_VIDEO_WIDTH")) {
								String s1 = l.substring(15);
								videoWidth = Integer.valueOf(s1);
							}
						}						
						//解析视频高度
						if (l.length() >= 15) {
							String s4 = l.substring(0, 15);							
							if (s4.equals("ID_VIDEO_HEIGHT")) {
								String s1 = l.substring(16);
								videoHeight = Integer.valueOf(s1);
								rate = (float) videoWidth/ (float) videoHeight;
								//解析好视频的宽度和高度后立即更新调整好视频面板。
								videoPanel.doLayout();
							}
						}

					}
				} catch (Throwable t) {
					t.printStackTrace();
				}
			}
		};

		t1 = new Thread(errorReader);
		t2 = new Thread(standReader);
		t1.start();
		t2.start();

		//监视mplayer退出
		Thread waitThread=new Thread (){
			public void run(){
				try {
					//使waitThread这个线程处于等待，直到proc这个进程已经终止（即停止播放，不是暂停而是关闭或播放结束）。
					//当proc这个进程终止，下面的方法才继续执行。
					proc.waitFor();
					
					t1.interrupt();
					t2.interrupt();
					//playComplete();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		};
		waitThread.start();
	}
	
	//退出程序
	public void exit(){
		if(proc!=null){
			proc.destroy();
		}
		//saveConfig();
		System.exit(0);
	}

	public float getRate() {
		return rate;
	}
	
	
	
	
	
	
	
	
	
	
	
	

}
